#include "util.h"

sem_t OK_to_access;

char onlinename[100][20];
char onlineip[100][20];
int mark[100];
int onlinenum;

int add_online_user(char name[], char ip[])
{
  sem_wait(&OK_to_access);

  strcpy(onlinename[onlinenum], name);
  strcpy(onlineip[onlinenum], ip);
  mark[onlinenum] = 1;
  onlinenum ++;

  sem_post(&OK_to_access);
  return 1;  
}

int remove_online_user(char name[], char ip[])
{
  int i, j;
  sem_wait(&OK_to_access);
  
  if(name != NULL)
  {
    for(i = 0; i < onlinenum; i++)
    {
      if(strcmp(name, onlinename[i]) == 0)
      {
        for(j = i; j < onlinenum - 1; j++)
        {
          strcpy(onlinename[j], onlinename[j + 1]);
          mark[j] = mark[j + 1];
        }
        for(j = i; j < onlinenum -1; j++)
        {
          strcpy(onlineip[j], onlineip[j + 1]);
        }
        onlinenum --;
        sem_post(&OK_to_access);
        return 1;  
      }
    } 
  }
  else if(ip != NULL)
  { 
    for(i = 0; i < onlinenum; i++)
    {
      if(strcmp(onlineip[i], ip) == 0)
      {
        for(j = i; j < onlinenum - 1; j++)
        {
          strcpy(onlineip[j], onlineip[j + 1]);
          mark[j] = mark[j + 1];
        }
        for(j = i; j < onlinenum - 1; j++)
        {
          strcpy(onlineip[j], onlineip[j + 1]);
        }
        onlinenum --;
        sem_post(&OK_to_access);
        return 1;
      }
    }
  }
  
  sem_post(&OK_to_access);
  return 0;
}

long getFileSize(char* filename)
{
  struct stat buf;
  
  if(stat(filename, &buf)<0)
    return 0;

  return (long)buf.st_size;
}

long get_file_size(char* path)
{
  long filesize = 0;
  FILE *fp;
  
  fp = fopen(path, "r");
  if(fp == NULL)
  {
    printf("%s\n", path);
    printf("get file size...file not found...\n");
    return filesize;
  }
  

  fseek(fp, 0L, SEEK_END);
  filesize = ftell(fp);
  fclose(fp);

  return filesize;
}

int charindex(char s[], int l)
{
        char c;
        int i = 0;
        while((c = s[i]) != l)
        {
                i++;
        }

        if( i >= strlen(s))
                i = -1;

        return i;
}



